package com.shujiaotong.controller;

import cn.hutool.crypto.digest.MD5;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shujiaotong.common.BaseContext;
import com.shujiaotong.common.R;
import com.shujiaotong.pojo.Admin;
import com.shujiaotong.service.AdminService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public R login(@RequestBody Admin admin, HttpSession session){
        log.info("登录信息：{}",admin);
        // 1. 获取用户名、密码
        String username = admin.getUsername();
        String password = admin.getPassword();
        password = MD5.create().digestHex(password);
        // 2. 根据用户名查询用户信息
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getUsername,username);
        Admin admin1 = adminService.getOne(qw);
        // 3. 用户信息查不到 -- 登用户名不存在
        if(StringUtils.isEmpty(admin1)){
            log.info("登用户名不存在");
            return R.error("登用户名不存在");
        }
        // 4. 比较密码 -- 不对 密码输入错误
        if(!admin1.getPassword().equals(password)){
            log.info("密码输入错误");
            return R.error("密码输入错误");
        }
        // 5. 是否禁用 -- 用户已禁用
        if(admin1.getStatus() == 0){
            log.info("用户已禁用");
            return R.error("用户已禁用");
        }
        // 6. 存会话 session
//    session.setAttribute("user",admin1.getId());
        redisTemplate.opsForValue().set(
                "auth"+admin1.getId(),admin1.getId(),
                30, TimeUnit.MINUTES
        );

        // 7. 返回数据 登录成功
        return R.success(admin1);
    }

    // 登出
    @GetMapping("logout")
    public R logout(){
        // 登出
//    session.removeAttribute("user");
        Long currentId = BaseContext.getCurrentId();
        redisTemplate.delete("auth"+currentId);
        return R.success("登出成功");
    }

    @GetMapping("page")
    public R page(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String name){
//        接收参数
        log.info("当前页:{},页条数:{},姓名:{}",page,pageSize,name);
//        分页条件
        Page<Admin> adminPage = new Page<>(page,pageSize);
//        查询条件
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Admin::getName,name);
        qw.orderByDesc(Admin::getUpdateTime);
//        分页查询
        adminService.page(adminPage,qw);
//        返回值
        return R.success(adminPage);

    }


    // 新增管理员
    @PostMapping
    public R save(@RequestBody Admin admin,HttpSession session){
        // 1. 接受参数
        log.info("新增数据：{}",admin);
        // 2. 字段处理
        String password = MD5.create().digestHex("123456");
        admin.setPassword(password);

        admin.setStatus(1);// 正常

//        admin.setCreateTime(LocalDateTime.now());// 当前时间
//        admin.setUpdateTime(LocalDateTime.now());// 当前时间
        // 从session获取当前登录的信息
//        Long user = (Long) session.getAttribute("user");
//        admin.setUpdateUser(user);
//        admin.setCreateUser(user);
        boolean b = adminService.save(admin);

        return b?R.success("新增成功"):R.error("新增失败");
    }

    @PutMapping("changeStatus")
    public R changeStatus(@RequestBody Admin admin){
        Admin admin1 = adminService.getById(admin.getId());
        if (admin1.getStatus()==0){
            admin1.setStatus(1);
            return adminService.updateById(admin1)?R.success("启用成功"):R.error("启用失败");
        }else {
            admin1.setStatus(0);
            return adminService.updateById(admin1)?R.success("禁用成功"):R.error("禁用失败");
        }
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Long id ){
        Admin adminId = adminService.getById(id);
        if(adminId != null){
            adminId.setPassword(MD5.create().digestHex(adminId.getPassword()));
            return R.success(adminId);
        }
        return R.error("查询失败");
    }

    @PutMapping
    public R update(@RequestBody Admin admin){
        admin.setPassword(MD5.create().digestHex(admin.getPassword()));
        boolean flag = adminService.updateById(admin);
        return flag ? R.success("修改成功") : R.error("修改失败");
    }


//    查询所有管理员
    @GetMapping
    public R list(){
        return R.success(adminService.list());
    }
}
